/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.service.dao;

//import com.citysoft.security.PassTranformer;
import com.myapp.util.ResourceBundleUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author toint
 */
public class BaseHibernateDAO {

    public static final ThreadLocal<Session> threadLocal = new ThreadLocal();
    public static Configuration configuration = new Configuration();
    public static SessionFactory sessionFactory;
    public static String configFile = "";

    private static void decryptDBConfig(Configuration dbConfig, String path) {
        if ("true".equals(dbConfig.getProperty("is_information_encrypted"))) {
            String[] propertiesToDecrypt = new String[6];
            propertiesToDecrypt[0] = "hibernate.connection.url";
            propertiesToDecrypt[1] = "hibernate.connection.username";
            propertiesToDecrypt[2] = "hibernate.connection.password";
            propertiesToDecrypt[3] = "connection.url";
            propertiesToDecrypt[4] = "connection.username";
            propertiesToDecrypt[5] = "connection.password";
            for (int i = 0; i < propertiesToDecrypt.length; i++) {
                if (dbConfig.getProperty(propertiesToDecrypt[i]) == null) {
                    continue;
                }
                try {
//                    dbConfig.setProperty(propertiesToDecrypt[i], PassTranformer.decrypt(dbConfig.getProperty(propertiesToDecrypt[i])));
                } catch (Exception ex) {
                    System.out.println("Lỗi giải mã thuộc tính \"" + propertiesToDecrypt[i] + "\" của file" + path);
                    ex.printStackTrace();
                }
            }
        } else {
            System.out.println("File " + path + ": is_information_encrypted is null or false");
        }
    }

    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session != null) {
            if (session.isOpen()) {
                session.close();
            }
            threadLocal.remove();
        }
        if (session == null || (!session.isOpen())) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = sessionFactory != null ? sessionFactory.openSession() : null;

            threadLocal.set(session);
        }
        return session;
    }

    public static Session openThreadSession()
            throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session != null) {
            if (session.isOpen()) {
                session.close();
            }
            threadLocal.remove();
        }

        if ((session == null) || (!session.isOpen())) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = sessionFactory != null ? sessionFactory.openSession() : null;

            threadLocal.set(session);
        }

        return session;
    }

    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    public static void closeSession()
            throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if ((session != null) && (session.isOpen())) {
            session.close();
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void setConfigFile(String configFile) {
        configFile = configFile;
        sessionFactory = null;
    }

    public static Configuration getConfiguration() {
        return configuration;
    }

    static {
        try {
            configFile = ResourceBundleUtil.getHibernateConfigFileLocation();
            configuration.configure(configFile);
            decryptDBConfig(configuration, configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

}
